<?php

// Authenticate
require("class.AuthenticationManager.php");
require("class.CommandMenu.php");
if (!$authenticationManager->isLoggedIn() || !$authenticationManager->hasClearance(CLEARANCE_ADMINISTRATOR)) {
  Header("Location: login.php?redirect=$_SERVER[PHP_SELF]&clearanceRequired=Administrator");
  exit;
}

// Connect to database.
$dbh = dbConnect();
$contextUser = strtolower($_SESSION['contextUser']);

//load local vars from superglobals
if (isset($_REQUEST['uid']))
  $uid = $_REQUEST['uid'];
else
  //get the first user from the database
  $uid = getFirstUser();

//define the command menu
include("timesheet_menu.inc");

if (isset($_REQUEST['cto']))
{
  $cto = $_REQUEST['cto'];
}
else
{
    //get the first cto
    $cto = getFirstCTO();
}
  
// Set default months
setReportDate($year, $month, $day, $next_week, $prev_week, $next_month, $prev_month, $time, $time_middle_month);  
  
// Change the date-format for internationalization...
if ($mode == "all") $mode = "monthly";
if ($mode == "weekly") {
  $query = "select   $TIMES_TABLE.proj_id, $TIMES_TABLE.task_id, $USER_TABLE.username, ".
                    "sec_to_time(unix_timestamp(end_time) - unix_timestamp(start_time)) as diff_time, ".
                    "(unix_timestamp(end_time) - unix_timestamp(start_time)) as diff, $PROJECT_TABLE.title, $TASK_TABLE.name, ".
                    "date_format(start_time, '%Y/%m/%d') as start_date, trans_num, $TIMES_TABLE.uid, ".
                    "$USER_TABLE.first_name, $USER_TABLE.last_name, $TIMES_TABLE.log_message " .
           "FROM     $USER_TABLE, $TIMES_TABLE, $PROJECT_TABLE, $TASK_TABLE ".
           "WHERE    $TIMES_TABLE.uid=$USER_TABLE.username ".
		   "AND      end_time > 0 ".
		   "AND      $USER_TABLE.cto='$cto' ".
		   "AND      start_time >= '$year-$month-$day' ".
		   "AND      $PROJECT_TABLE.proj_id = $TIMES_TABLE.proj_id ".
		   "AND      $TASK_TABLE.task_id = $TIMES_TABLE.task_id ".
		   "AND      end_time < '".date("Y-m-d",$next_week)."' ".
		   "order by $USER_TABLE.uid, task_id, start_time";
} else {
  $query = "select   $TIMES_TABLE.proj_id, $TIMES_TABLE.task_id, $USER_TABLE.username, sec_to_time(unix_timestamp(end_time) - unix_timestamp(start_time)) as diff_time, ".
                    "(unix_timestamp(end_time) - unix_timestamp(start_time)) as diff, $PROJECT_TABLE.title, $TASK_TABLE.name, ".
                    "date_format(start_time, '%Y/%m/%d') as start_date, trans_num, $TIMES_TABLE.uid, ".
                    "$USER_TABLE.first_name, $USER_TABLE.last_name, $TIMES_TABLE.log_message " .
           "from     $USER_TABLE, $TIMES_TABLE, $PROJECT_TABLE, $TASK_TABLE ".
           "WHERE    $TIMES_TABLE.uid=$USER_TABLE.username ".
		   "AND      end_time > 0  ".
		   "AND      $USER_TABLE.cto='$cto' ".
		   "AND      start_time >= '$year-$month-1' ".
		   "AND      $PROJECT_TABLE.proj_id = $TIMES_TABLE.proj_id ".
		   "AND      $TASK_TABLE.task_id = $TIMES_TABLE.task_id ".
		   "AND      end_time < '".date("Y-m-1",$next_month)."' ".
		   "order by $USER_TABLE.uid, start_time, title, name ";
}


 $queryBis = "select   $USER_TABLE.first_name, $USER_TABLE.last_name " .
             "from     $USER_TABLE ".
             "WHERE    $USER_TABLE.cto='$cto' ";



// Run the query  
list($qh,$num) = dbQuery($query);

// Run the query  
list($qhBis,$numBis) = dbQuery($queryBis);
  
// Define working varibales  
$last_uid         = -1;
$last_task_id     = -1;
$total_time       = 0;
$grand_total_time = 0;

?>
<html>
<head>
<title>Timesheet.php Report: Days for a specific project</title>
<?php include ("header.inc"); ?>


<script language="Javascript">

function remindByMail()
{
    <?php
    // To
    $to = 'abdelmajid.maayay@silkan.com';
     
    // Subject
    $subject = 'Developpez.com - Test Mail';
     
    // Headers
    $headers = 'Mime-Version: 1.0'."\r\n";
    $headers .= 'Content-type: text/html; charset=utf-8'."\r\n";
    $headers .= "\r\n";
     
    // Message
    $msg = '<strong>Developpez.com</strong> - Message du mail ...';
     
    // Function mail()
    mail($to, $subject, $msg, $headers);
    ?>

}

</script>


</head>
<body <?php include ("body.inc"); ?> >
<?php include ("banner.inc"); ?>

<form action="monthly_imputation_state.php" method="get">
<input type="hidden" name="month" value="<?php echo $month; ?>">
<input type="hidden" name="year" value="<?php echo $year; ?>">
<input type="hidden" name="day" value="<?php echo $day; ?>">
<input type="hidden" name="mode" value="<?php echo $mode; ?>">


<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="100%" class="face_padding_cell">
        <table width="100%" border="0">
            <tr>
                <td align="left" nowrap>
                    <table width="100%" height="100%" border="0" cellpadding="1" cellspacing="2">
                        <tr>                      
                            <td align="right" width="0" class="outer_table_heading">CTO:</td>
                            <td align="left" width="50%">
                                <?php cto_select_droplist($cto); ?>
                            </td>
							<td align="center" width="50%" class="outer_table_heading" >
                                <?php 
								if($year > date('Y'))
								{
								    $dateOfDay = 0;
								}
								if($year == date('Y'))
								{
								    if($month < date('n'))
								    {
								        $dateOfDay = date('t',mktime(0,0,0,$month, 1, $year));
								    }
									if($month == date('n'))
									{
								        $dateOfDay = date('d');
								    }
									if($month > date('n'))
									{
								    
								        $dateOfDay = 0;
								    }
								}
								if($year < date('Y'))
								{
								    $dateOfDay = 0;
								}
								
								$nbWE = 0;
								$k = 0;
								while ($k < $dateOfDay)
								{
									if (date('D',mktime(0,0,0,$month,$dateOfDay - $k,$year)) == "Sat" || date('D',mktime(0,0,0,$month,$dateOfDay - $k,$year)) == "Sun" )
									{
										$nbWE = $nbWE + 1;
									}
									$k = $k + 1;
                                }							
								echo "Number of working days : ";
								echo $dateOfDay - $nbWE;
                                if ($dateOfDay - $nbWE < 3)
								{
								    echo " day";
								} else {
								    echo " days";
								}
								?>
                            </td>
                        </tr>
                    </table>
                </td>                      
                <td align="center" nowrap class="outer_table_heading">
                    <?php 
                    if ($mode == "weekly")
					{
                        echo date('F d, Y',$time); 
                    }
					else
                    {
					    echo date('F Y',$time);
                    }
                    ?>
                </td>                        
                <td align="right" nowrap>
                    <?php printPrevNext($time, $next_week, $prev_week, $next_month, $prev_month, $time_middle_month,"cto=$cto", $mode); ?>
                </td>
            </tr>
        </table>
        <table width="100%" align="center" border="0" cellpadding="0" cellspacing="0" class="outer_table">
            <tr>
                <td>      
                    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="table_body">
                        <?php   
						if ($num == 0) {
                            print "  <tr>\n";
                            print "    <td align=\"center\">\n";
                            print "      <i><br>No days recorded.<br><br></i>\n";
                            print "    </td>\n";
                            print "  </tr>\n";
                        } else {
                            while ($data = dbResult($qh)) 
							{
                                // New project, so print out last project total time and start a new table cell.
                                if ($last_uid != $data["uid"]) 
								{
                                    $last_uid = $data["uid"];
                                    if ($grand_total_time) 
									{
                                        $formatted_time = $total_time /60 / 60/ 8;
										if ($dateOfDay - $nbWE > $formatted_time)
								        {
                                            print "<tr><td colspan=\"4\" align=\"right\" class=\"calendar_totals_line_weekly_right_red\">" .
                                                      "Total: <span class=\"calendar_total_value_weekly\">$formatted_time days</span></td></tr>\n";
								        } else {
							                print "<tr><td colspan=\"4\" align=\"right\" class=\"calendar_totals_line_weekly_right\">" .
                                                      "Total: <span class=\"calendar_total_value_weekly\">$formatted_time days</span></td></tr>\n";
								        }
                                    }
                              
                                    print "<tr>\n\t<td colspan=\"4\" valign=\"top\" class=\"calendar_cell_disabled_right\">" .
                                    stripslashes("$data[first_name] $data[last_name]")."</td></tr>\n";
                                    $total_time = 0;
                                }
							  
							 
							  
                                print "<tr>\n\t";
							    
							     // Start date:
                        	    print "<td valign=\"top\" align=\"left\" width=\"12%\" class=\"calendar_cell_right\">$data[start_date]&nbsp;&nbsp;</td>\n\t";
                                print "</td>\n\t";
							    
							    // Project Title:
							    print "<td valign=\"top\" align=\"left\"  class=\"calendar_cell_right\">\n\t";
                                $current_project_title = stripslashes($data["title"]);
                                print "\t<a href=\"javascript:void(0)\" onclick=\"javascript:window.open('proj_info.php?proj_id=$data[proj_id]','Task Info','location=0,directories=no,status=no,scrollbar=yes,menubar=no,resizable=1,width=300,height=150')\">$current_project_title</a>\n\t";
                                print "&nbsp;</td>\n\t";
							    
							    // Task Name:
							    print "<td valign=\"top\" align=\"left\"  class=\"calendar_cell_right\">\n\t";
                                $current_task_name = stripslashes($data["name"]);
                                print "\t<a href=\"javascript:void(0)\" onclick=\"javascript:window.open('task_info.php?task_id=$data[task_id]','Task Info','location=0,directories=no,status=no,scrollbar=yes,menubar=no,resizable=1,width=300,height=150')\">$current_task_name</a>\n\t";
                                print "&nbsp;</td>\n\t";

                        	    // Duration
                        	    $duration = $data["diff"]/3600 / 8;
                                print "<td valign=\"bottom\" align=\"right\" width=\"6%\" class=\"calendar_cell_right\">\n\t\t";
                                print "&nbsp;&nbsp;$duration days<a>\n\t</td>\n</tr>\n";
                                $total_time += $data["diff"];
                                $grand_total_time += $data["diff"];
                            }
                            if ($total_time) 
							{
                                $formatted_time = $total_time / 60 / 60 / 8;
								if ($dateOfDay - $nbWE > $formatted_time)
								{
                                    print "<tr><td colspan=\"4\" align=\"right\" class=\"calendar_totals_line_weekly_right_red\">" .
                                          "Total: <span class=\"calendar_total_value_weekly\">$formatted_time days</span></td></tr>";
								} else {
							        print "<tr><td colspan=\"4\" align=\"right\" class=\"calendar_totals_line_weekly_right\">" .
                                          "Total: <span class=\"calendar_total_value_weekly\">$formatted_time days</span></td></tr>";
								}
                            }
                            $formatted_time = $grand_total_time / 60 / 60 / 8;
                        }
						
						//////////////////////////////////////////////////////////////////////////////////////////////////////////////
						
						
						if ($numBis != 0) {
							while ($dataBis = dbResult($qhBis)) 
							{
		     					// Run the query  
                                list($qh,$num) = dbQuery($query);
							    $toPrint = 1;
							    while ($data = dbResult($qh)) 
							    {
								    if ($data['first_name'] == $dataBis['first_name'] && $data['last_name'] == $dataBis['last_name'])
									{
									    $toPrint = 0;
									}
								}
								if ($toPrint == 1)
								{
								    print "<tr>\n\t<td colspan=\"4\" valign=\"top\" class=\"calendar_cell_disabled_right\">" .
                                           stripslashes("$dataBis[first_name] $dataBis[last_name]")."</td></tr>\n";
							        print "<tr><td colspan=\"4\" align=\"right\" class=\"calendar_totals_line_weekly_right_red\">" .
                                          "Total: <span class=\"calendar_total_value_weekly\">0 day</span></td></tr>";
							    }
							}
							
                        }
						///////////////////////////////////////////////////////////////////////////////////////////////////////////////
                        ?>
                             </tr>
                         </td>
                    </table>
                </td>
            </tr>
<?php 
  if ($num > 0)
  {
?>
    <tr>
      <td>
        <table width="100%" border="0" cellspacing="0" cellpadding="0" class="table_bottom_panel">
          <tr>
            <td align="right" class="calendar_totals_line_monthly">
<?php
  if ($mode == "weekly")
    print "Weekly";
  else
    print "Monthly";
?>            
              total:
              <span class="calendar_total_value_monthly"><?php echo $formatted_time ; echo " days"; ?></span>
            </td>
          </tr>
        </table>
      </td>
    </tr>
<?php
  }
?>
  </table>
  

    </td>
  </tr>
</table>
<!--
 		<table width="100%" border="0" cellspacing="0" cellpadding="0">
	        <tr>
	        	<td align="center" nowrap>
	        	   <a href="remind_by_mail.php?month=
				   <!--?php print $month; ?>&year=<!--?php print $year; ?>&query=<!--?php print $query; ?>&cto=<!?php print $cto; ?>
				   &mode=monthly">
				       <input name="downloadButton" type="button" id="downloadButton" value="Download" onClick="DownloadMonthlyImputation()"> </input> 
				   </a>
				   <br><br>
	        	</td>
	        </tr>
        </table>   
 		<table width="100%" border="0" cellspacing="0" cellpadding="0">
	        <tr>
	        	<td align="center" nowrap>
	        	   <a>
				       <input name="remindButton" type="button" id="remindButton" value="Remind" onClick="remindByMail()"> </input> 
				   </a>
				   <br><br>
	        	</td>
	        </tr>
        </table>   
	-->	
		
</form>
<?php include ("footer.inc");
?>
</BODY>
</HTML>


